namespace IMPlant.Core.Web.Control.Helper
{
    using IMPlant.Core.Web.Control;
    using System;
    using System.Data;
    using System.IO;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Xml;
    using System.Xml.XPath;
    using System.Xml.Xsl;

    public class Common
    {
        private static void CreateStylesheet(XmlTextWriter writer, string[] headers, string[] fields, ExportFormat exportFormat)
        {
            string ns = "http://www.w3.org/1999/XSL/Transform";
            writer.Formatting = Formatting.Indented;
            writer.WriteStartDocument();
            writer.WriteStartElement("xsl", "stylesheet", ns);
            writer.WriteAttributeString("version", "1.0");
            writer.WriteStartElement("xsl:output");
            writer.WriteAttributeString("method", "text");
            writer.WriteAttributeString("version", "4.0");
            writer.WriteEndElement();
            writer.WriteStartElement("xsl:template");
            writer.WriteAttributeString("match", "/");
            for (int i = 0; i < headers.Length; i++)
            {
                writer.WriteString("\"");
                writer.WriteStartElement("xsl:value-of");
                writer.WriteAttributeString("select", "'" + headers[i] + "'");
                writer.WriteEndElement();
                writer.WriteString("\"");
                if (i != (fields.Length - 1))
                {
                    writer.WriteString((exportFormat == ExportFormat.CSV) ? "," : "\t");
                }
            }
            writer.WriteStartElement("xsl:for-each");
            writer.WriteAttributeString("select", "Export/Values");
            writer.WriteString("\r\n");
            for (int j = 0; j < fields.Length; j++)
            {
                writer.WriteString("\"");
                writer.WriteStartElement("xsl:value-of");
                writer.WriteAttributeString("select", fields[j]);
                writer.WriteEndElement();
                writer.WriteString("\"");
                if (j != (fields.Length - 1))
                {
                    writer.WriteString((exportFormat == ExportFormat.CSV) ? "," : "\t");
                }
            }
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndElement();
        }

        public static void Export(DataTable dt, ExportFormat exportFormat, string fileName, Encoding encoding)
        {
            DataSet ds = new DataSet("Export");
            DataTable table = dt.Copy();
            table.TableName = "Values";
            ds.Tables.Add(table);
            string[] headers = new string[table.Columns.Count];
            string[] fields = new string[table.Columns.Count];
            for (int i = 0; i < table.Columns.Count; i++)
            {
                headers[i] = table.Columns[i].Caption;
                fields[i] = ReplaceSpecialChars(table.Columns[i].ColumnName);
            }
            Export(ds, headers, fields, exportFormat, fileName, encoding);
        }

        public static void Export(DataTable dt, int[] columnIndexList, ExportFormat exportFormat, string fileName, Encoding encoding)
        {
            DataSet ds = new DataSet("Export");
            DataTable table = dt.Copy();
            table.TableName = "Values";
            ds.Tables.Add(table);
            string[] headers = new string[columnIndexList.Length];
            string[] fields = new string[columnIndexList.Length];
            for (int i = 0; i < columnIndexList.Length; i++)
            {
                headers[i] = table.Columns[columnIndexList[i]].Caption;
                fields[i] = ReplaceSpecialChars(table.Columns[columnIndexList[i]].ColumnName);
            }
            Export(ds, headers, fields, exportFormat, fileName, encoding);
        }

        private static void Export(DataSet ds, string[] headers, string[] fields, ExportFormat exportFormat, string fileName, Encoding encoding)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ContentType = string.Format("text/{0}", exportFormat.ToString().ToLower());
            HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.{1}", HttpUtility.UrlEncode(fileName, Encoding.UTF8), exportFormat.ToString().ToLower()));
            HttpContext.Current.Response.ContentEncoding = encoding;
            MemoryStream w = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(w, encoding);
            CreateStylesheet(writer, headers, fields, exportFormat);
            writer.Flush();
            w.Seek(0L, SeekOrigin.Begin);
            XmlDataDocument document = new XmlDataDocument(ds);
            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(new XmlTextReader(w));
            StringWriter writer2 = new StringWriter();
            transform.Transform((IXPathNavigable) document, null, (TextWriter) writer2);
            HttpContext.Current.Response.Write(writer2.ToString());
            writer2.Close();
            writer.Close();
            w.Close();
            HttpContext.Current.Response.End();
        }

        public static void Export(DataTable dt, int[] columnIndexList, string[] headers, ExportFormat exportFormat, string fileName, Encoding encoding)
        {
            DataSet ds = new DataSet("Export");
            DataTable table = dt.Copy();
            table.TableName = "Values";
            ds.Tables.Add(table);
            string[] fields = new string[columnIndexList.Length];
            for (int i = 0; i < columnIndexList.Length; i++)
            {
                fields[i] = ReplaceSpecialChars(table.Columns[columnIndexList[i]].ColumnName);
            }
            Export(ds, headers, fields, exportFormat, fileName, encoding);
        }

        public static string GetChildControlPrefix(Control control)
        {
            if (control.NamingContainer.Parent == null)
            {
                return control.ID;
            }
            return string.Format("{0}_{1}", control.NamingContainer.ClientID, control.ID);
        }

        public static string ReplaceCommaChars(string input)
        {
            if (!string.IsNullOrEmpty(input))
            {
                input = input.Replace("，", ",").Replace("；", ";");
            }
            return input;
        }

        public static string ReplaceSpecialChars(string input)
        {
            if (!string.IsNullOrEmpty(input))
            {
                input = input.Replace(" ", "_x0020_").Replace("%", "_x0025_").Replace("#", "_x0023_").Replace("&", "_x0026_").Replace("/", "_x002F_");
            }
            return input;
        }

        public static void SetAttribute(IAttributeAccessor iaa, string key, string value, AttributeValuePosition csp)
        {
            SetAttribute(iaa, key, value, csp, ';');
        }

        public static void SetAttribute(IAttributeAccessor iaa, string key, string value, AttributeValuePosition csp, char separator)
        {
            string attribute = iaa.GetAttribute(key);
            if (string.IsNullOrEmpty(attribute))
            {
                iaa.SetAttribute(key, value);
            }
            else if (csp == AttributeValuePosition.First)
            {
                attribute = attribute.TrimStart(new char[] { separator });
                iaa.SetAttribute(key, value + separator + attribute);
            }
            else if (csp == AttributeValuePosition.Last)
            {
                iaa.SetAttribute(key, attribute.TrimEnd(new char[] { separator }) + separator + value);
            }
        }
    }
}

